<template>
  <el-form
    ref="registerForm"
    :model="form"
    label-width="80px"
    style="width: 30%; margin-left: 30%"
  >
    <el-form-item label="用户名">
      <el-input v-model="form.account"></el-input>
    </el-form-item>

    <el-form-item label="密码">
      <el-input
        v-model="form.password"
        placeholder="请输入密码"
        show-password
      ></el-input>
    </el-form-item>

    <el-form-item label="姓名">
      <el-input v-model="form.name"></el-input>
    </el-form-item>

    <el-form-item label="性别">
      <el-radio-group v-model="form.gender">
        <el-radio label="男"></el-radio>
        <el-radio label="女"></el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="身份证号">
      <el-input v-model="form.idCard"></el-input>
    </el-form-item>

    <el-form-item label="居住地">
      <el-input v-model="form.area"></el-input>
    </el-form-item>

    <el-form-item label="出生日期">
      <el-date-picker
        v-model="form.birthDate"
        type="date"
        placeholder="选择日期"
      >
      </el-date-picker>
    </el-form-item>

    <el-form-item label="政治面貌">
      <el-select v-model="form.politicsStatus" placeholder="请选择">
        <el-option v-for="v in status" :key="v" :value="v" :label="v">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">
        {{ btnmsg[change] }}
      </el-button>

      <el-button @click="handleCancle">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { register, updateUser } from "@/api/user";

export default {
  name: "PersonForm",
  data() {
    return {
      form: {
        account: "",
        password: "",
        name: "",
        gender: "",
        idCard: "",
        area: "",
        birthDate: "",
        politicsStatus: "",
      },
      change: undefined,
      btnmsg: ["确认修改", "注册"],
      status: ["共产党员", "共青团员", "无党派人士"],
    };
  },
  created() {
    this.change = this.$route.params.change;
    if (this.change === "0") {
      this.currentUser();
    }
  },
  methods: {
    onSubmit() {
      if (this.change === 1) {
        register(this.form).then((res) => {
          let msg = res.msg;
          if (msg === "注册成功") {
            this.$message.success(msg);
            this.$router.push("/list");
          } else {
            this.$message.error(msg);
          }
        });
      }else {
        updateUser(this.form).then(res => {
          this.$message.success(res.msg+',请重新登录');
          sessionStorage.removeItem("token");
          this.$router.push('/login')
        })
      }
    },
    handleCancle() {
      this.$refs.registerForm.clearValidate();
      this.$router.push("/list");
    },
    currentUser() {
      Object.assign(this.form, this.$store.state.userInfo);
    },
  },
};
</script>